#include "LocalSocket.h"
#include "handlers/UnlockDevice.h"
#include "handlers/Refresh.h"
#include <QDebug>

LocalSocket::LocalSocket(QObject *parent) : QObject(parent)
{
    m_timerReconnect = new QTimer(this);
    m_timerReconnect->setInterval(2000);
    m_timerReconnect->setSingleShot(false);
    connect(m_timerReconnect, SIGNAL(timeout()), this, SLOT(onReconnect()));

    m_socket = new QTcpSocket(this);
    connect(m_socket, SIGNAL(disconnected()), this, SLOT(onSocketDisconnected()));
    connect(m_socket, SIGNAL(connected()), this, SLOT(onSocketConnected()));
    connect(UnlockDevice::instance(), SIGNAL(writeCmd(QString)), this, SLOT(onWrite(QString)), Qt::QueuedConnection);
    connect(Refresh::instance(), SIGNAL(writeCmd(QString)), this, SLOT(onWrite(QString)), Qt::QueuedConnection);

    m_timerReconnect->start();
}

void LocalSocket::onSocketDisconnected()
{
    qDebug() << "local socket disconnected, start to reconnect in 1 second...";
    m_timerReconnect->start();
}

void LocalSocket::onSocketConnected()
{
    qDebug() << "local socket connected!";
    m_timerReconnect->stop();
}

void LocalSocket::onWrite(const QString& cmd)
{
    m_socket->write(cmd.toUtf8());
}

void LocalSocket::onReconnect()
{
    qDebug() << "reconnecting...";
    m_socket->disconnectFromHost();
    m_socket->disconnect();
    m_socket->connectToHost("127.0.0.1", 10001);
    connect(m_socket, SIGNAL(disconnected()), this, SLOT(onSocketDisconnected()));
    connect(m_socket, SIGNAL(connected()), this, SLOT(onSocketConnected()));
}
